<template>
  <div class="archive-panel">
    <!-- 顶部装饰条 -->
    <div class="panel-content">
      <!-- 分组选择区域 - 仅保留选择功能 -->

      <!-- 标签区域 -->
      <div class="tags-section">
        <div class="tags-header">
          <input type="text" v-model="newTag" placeholder="输入标签名称..." @keyup.enter="addCustomTag"
            ref="customTagInput" />
          <button class="add-custom-tag-btn" @click="addCustomTag">
            <i class="fa iconfont lricon-tianjia"></i>
            添加标签
          </button>
        </div>

        <!-- 已选标签 -->
        <div class="selected-tags" v-if="selectedTags.length > 0">
          <div class="tag-item" v-for="(tag, index) in selectedTags" :key="index">
            {{ tag }}
            <button class="remove-tag" @click="removeTag(index)">
              <i class="fa iconfont lricon-shanchu1" style="font-size: 12rem;color: white;"></i>
            </button>
          </div>
        </div>

        <!-- 预设标签 -->
        <div class="preset-tags">
          <button class="tag-btn" v-for="(tag, index) in presetTags" :key="index"
            :class="{ selected: selectedTags.includes(tag) }" @click="toggleTag(tag)">
            {{ tag }}
          </button>
        </div>

      </div>
      <div class="name_group">
        <div class="name">

          <input v-model="localGuazhu" class="name_input" type="text" placeholder="请输入占测人姓名">
          <div class="icon"><i style="font-size: 18rem;" class="iconfont lricon-xingming"></i></div>
        </div>
        <div @click="() => {
          emitter.emit('ppShowGroupSlc', true)
        }" class="group">
          <span> {{ localFenzu }} </span>
          <i class="iconfont lricon-zhufenzu"></i>
        </div>
      </div>



      <!-- 三个输入区域 -->
      <div class="input-sections">


        <!-- 肇事缘由输入 -->
        <div class="input-section">
          <div class="floating-label-container">
            <textarea v-model="localZhanshi" class="feedback-input" :class="{ focused: isFocused.title || localZhanshi }"
              :style="{ minHeight: '80rem' }" @input="handleTitleChange" @focus="setFocus('title', true)"
              @blur="setFocus('title', false)"></textarea>
            <label class="floating-label" :class="{ active: isFocused.title || localZhanshi }">
              请输入占问的事情...
            </label>
            <div class="char-count">{{ localZhanshi.length }} 字</div>
          </div>
        </div>

        <!-- 评语输入 -->
        <div class="input-section">
          <div class="floating-label-container">
            <textarea v-model="localDuanyu" class="feedback-input"
              :class="{ focused: isFocused.comment ||localDuanyu }" :style="{ minHeight: '80rem' }"
              @input="handleCommentChange" @focus="setFocus('comment', true)"
              @blur="setFocus('comment', false)"></textarea>
            <label class="floating-label" :class="{ active: isFocused.comment ||localDuanyu }">
              请输入对占事的断语...
            </label>
            <div class="char-count">{{localDuanyu.length }} 字</div>
          </div>
        </div>

        <!-- 反馈输入 -->
        <div class="input-section">
          <div class="floating-label-container">
            <textarea v-model="localFankui" class="feedback-input"
              :class="{ focused: isFocused.feedback || localFankui }" :style="{ minHeight: '80rem' }"
              @input="handleFeedbackChange" @focus="setFocus('feedback', true)"
              @blur="setFocus('feedback', false)"></textarea>
            <label class="floating-label" :class="{ active: isFocused.feedback || localFankui }">
              请输入占事的反馈...
            </label>
            <div class="char-count">{{ localFankui.length }} 字</div>
          </div>
        </div>

        <!-- 总字数统计 -->
        <div class="total-char-count">总字数: {{ totalCharacterCount }} 字</div>
      </div>
      <VanButton @click="save" style="width: 80vw;height: 34rem;margin-left: 
         7vw; font-size: 15rem;font-weight: bold;margin-bottom: 45rem;" block color="red" round>保存课例</VanButton>
    </div>

  </div>
</template>

<script>
import Multiselect from 'vue-multiselect'
import { Button } from 'vant';
import { Overlay, Picker, Popup } from 'vant';
import { Store, getStore } from '@tauri-apps/plugin-store';
import { show } from '@tauri-apps/api/app';
import emitter from '../bus/emitter';
export default {
  props: {
    tagList: {
      type: Array,
      default: () => [],
    },

    guaZhu: {
      type: String,
      default: ''
    },
    // 字符串类型 - 占事原因
    title: {
      type: String,
      default: "",
    },
     fenZu: {
      type: String,
      default: "",
    },

    // 字符串类型 - 评语
    comment: {
      type: String,
      default: "",
    },

    // 字符串类型 - 反馈
    feedback: {
      type: String,
      default: "",
    },
  },
  components: {
    VanButton: Button,
    Overlay,
    Multiselect,
    VanPicker: Picker,
    VanPopup: Popup
  },
  data() {
    return {
      // 本地数据，用于v-model绑定
      localZhanshi: this.title,
     localDuanyu: this.comment,
      localFankui: this.feedback,
      localGuazhu: this.guaZhu,
      localFenzu: this.fenZu,
      isFocused: {
        title: false,
        comment: false,
        feedback: false,
      },
      // 标签相关
      presetTags: [
        "婚姻",
        "前程",
        "求财",
        "疾病",
        "学业",
        "工作",
        "谒贵",
        "家庭",
        "出行",
        "决策",
      ],
      selectedTags: this.tagList,
      newTag: "",
      showCustomTagInput: false,
      groupValue: '朋友',
      options: [],
      showGroupSlc: true,
      emitter: emitter,
      username: ''
    };
  },
  async created() {
    emitter.on('ppGroupSlcV', (v) => {
      this.localFenzu = v[0]
    })
  },
  computed: {
    totalCharacterCount() {
      return (
        this.localZhanshi.length + this.localDuanyu.length + this.localFankui.length
      );
    },
    // 获取当前选中的分组名称
    selectedGroupName() {
      const group = this.groups.find((g) => g.id === this.selectedGroup);
      return group ? group.name : "";
    },
  },
  methods: {
    save() {
      emitter.emit('ppSave', {
        guaZhu: this.localGuazhu,
        tag: this.selectedTags,
        zhanShi: this.localZhanshi,
        duanYu: this.localDuanyu,
        fanKui: this.localFankui,
        fenZu: this.localFenzu,
        guaShi: '***'
      })
    },


    setFocus(field, isFocused) {
      this.isFocused[field] = isFocused;
    },

    // 处理标题变化，通知父组件
    handleTitleChange(e) {
      this.autoResize(e.target);
      this.$emit("update:title", this.localZhanshi);
    },

    // 处理评语变化，通知父组件
    handleCommentChange(e) {
      this.autoResize(e.target);
      this.$emit("update:comment", this.localDuanyu);
    },

    // 处理反馈变化，通知父组件
    handleFeedbackChange(e) {
      this.autoResize(e.target);
      this.$emit("update:feedback", this.localFankui);
    },

    autoResize(textarea) {
      textarea.style.height = "auto";
      const maxHeight = (0.6 * window.innerHeight) / 3;
      textarea.style.height = Math.min(textarea.scrollHeight, maxHeight) + "rem";
    },

    exportArchive() {
      this.$emit("export-archive", {
        ...this.getArchiveData(),
        tags: this.selectedTags,
        groupId: this.selectedGroup,
        groupName: this.selectedGroupName,
      });
      alert("存档已导出");
    },

    saveArchive() {
      if (
        !this.localZhanshi.trim() &&
        !this.localDuanyu.trim() &&
        !this.localFankui.trim() &&
        this.selectedTags.length === 0
      ) {
        alert("请至少填写一个字段内容或添加一个标签");
        return;
      }

      const newRecord = {
        ...this.getArchiveData(),
        tags: this.selectedTags,
        groupId: this.selectedGroup,
        groupName: this.selectedGroupName,
      };

      this.$emit("add-record", newRecord);
      this.$emit("save-archive", newRecord);
      alert("存档已保存");
    },

    getArchiveData() {
      const now = new Date();
      const formattedTime = `${now.getFullYear()}-${(now.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${now
          .getDate()
          .toString()
          .padStart(2, "0")} ${now
            .getHours()
            .toString()
            .padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}`;

      return {
        time: formattedTime,
        title: this.localZhanshi.trim(),
        comment: this.localDuanyu.trim(),
        feedback: this.localFankui.trim(),
      };
    },

    // 标签相关方法
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag);
      if (index > -1) {
        this.selectedTags.splice(index, 1);
      } else {
        this.selectedTags.push(tag);
      }
    },

    removeTag(index) {
      this.selectedTags.splice(index, 1);
    },

    addCustomTag() {
      const tag = this.newTag.trim();
      if (tag && !this.selectedTags.includes(tag) && !this.presetTags.includes(tag)) {
        this.selectedTags.push(tag);
        this.presetTags.push(tag);
        this.newTag = "";
        this.showCustomTagInput = false;
        this.$emit("add-custom-tag", tag);
      } else if (this.selectedTags.includes(tag) || this.presetTags.includes(tag)) {
        alert("该标签已存在");
      } else {
        alert("请输入有效的标签名称");
      }
    },


  },
  watch: {
    title(newVal) {
      this.localZhanshi = newVal;
    },
    comment(newVal) {
      this.localDuanyu = newVal;
    },
    feedback(newVal) {
      this.localFankui = newVal;
    },
    groups(newVal) {
      // 确保选中的分组仍然存在
      if (
        newVal.length &&
        this.selectedGroup &&
        !newVal.some((g) => g.id === this.selectedGroup)
      ) {
        this.selectedGroup = "";
      }
    },
    showCustomTagInput(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.customTagInput?.focus();
        });
      }
    },
  },
  mounted() {
    const textareas = document.querySelectorAll(".feedback-input");
    textareas.forEach((textarea) => this.autoResize(textarea));
  },
};
</script>

<style lang="scss" scoped>
/* 颜色定义 - 保持与分组管理面板一致 */
$lcbgc: var(--lr_lcbgc);
$lbgc: var(--lr_lbgc);
$primary: #9e2a2b;
$primary-light: #fff1f1;
$primary-dark: #720909;
$secondary: #8b4513;
$secondary-light: whitesmoke;
$accent: #523e20;
$accent-light: #f9f2e6;
$text-primary: #332720;
$text-secondary: #6b5a4b;
$background: #ffffff;
$danger: #a62f00;
$overlay: rgba(51, 39, 32, 0.6);
$border-hover: #b88d50;
$border-color: #efefef;

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Noto Serif SC", "SimSun", serif;
}

.archive-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100vw;
  height: calc(100vh - 135rem - var(--safe-top));
  border-radius: 4rem;
  align-items: center;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: scroll;
}

.panel-content {

  // 隐藏滚动条但保留滚动功能
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 和 Edge */

  &::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari 和 Opera */
  }

}

// 分组选择区域样式 - 优化下拉框样式
.group-section {
  width: 94vw;
  margin: 0 auto 16rem;
  padding: 12rem;
  background-color: $lcbgc;
  border-radius: 6rem;

  .group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rem;
  }

  .section-title {
    margin-bottom: 0;
    font-size: 16rem;
  }

  .group-selector {
    text-align: center;
    border: 1rem solid #959292;
    width: 94vw;
    line-height: 34rem;
    font-size: 15rem;
    border-radius: 6rem;
    height: 34rem;
  }



}

// 标签区域样式
.tags-section {
  width: 94vw;
  margin: 0 auto 16rem;
  padding: 12rem;
  background-color: $lcbgc;
  border-radius: 6rem;

  .tags-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rem;
  }

  input {
    flex-grow: 1;
    height: 30rem;
    padding: 3rem;
    border-radius: 18rem;
    outline: none;
    font-size: 15rem;
    margin-right: 10rem;
    border: 2rem solid var(--cart_bg_color);
  }

  .add-custom-tag-btn {
    // background-color: var(--cart_bg_color);
    color: rgb(0, 0, 0);
    background-color: $lcbgc;
    border: none;
    border-radius: 3rem;
    font-size: 16rem;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 5rem;

    &:active {
      background-color: #a3a3a3;
    }
  }

  // 已选标签
  .selected-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8rem;
    margin-bottom: 12rem;
    padding-bottom: 8rem;

  }

  .tag-item {
    background-color: #582b39;
    color: white;
    padding: 2rem 6rem;
    border-radius: 16rem;
    font-size: 13rem;
    display: flex;
    align-items: center;
    gap: 5rem;
    box-shadow: 0 1rem 2rem rgba(51, 39, 32, 0.1);
    transition: transform 0.2s ease;

    &:active {
      transform: translateY(-1rem);
    }

    .remove-tag {
      background: none;
      border: none;
      color: $primary;
      cursor: pointer;
      font-size: 11rem;
      display: flex;
      align-items: center;

      &:active {
        color: $primary-dark;
      }
    }
  }


  // 预设标签
  .preset-tags {
    padding-top: 10rem;
    border-top: 1rem dashed $border-color;
    display: flex;
    flex-wrap: wrap;
    gap: 8rem;
  }

  .tag-btn {
    background-color: $lbgc;
    color: black;
    border: 1rem none;
    padding: 2rem 9rem;
    border-radius: 16rem;
    font-size: 13rem;
    cursor: pointer;
    transition: all 0.2s ease;

    &:active {
      background-color: $accent-light;
      color: $accent;
      border-color: $accent;
    }

    &.selected {
      background-color: #56423e;
      color: white;
      border-color: $primary;
    }
  }
}

.name_group {
  width: 94vw;
  height: fit-content;
  display: flex;
  justify-content: space-between;
  margin-top: 5rem;
  align-items: center;

  .group {
    margin-top: 5rem;
    height: 34rem;
    line-height: 34rem;
    width: 100rem;
    height: 40rem;
    border-radius: 6rem;
    background-color: white;
    display: flex;
    border: 1rem solid $border-color;
    justify-content: space-around;
    align-items: center;
    font-size: 15rem;

    i {
      font-size: 18rem;
      color: var(--cart_bg_color);
    }
  }

  .name {
    flex-grow: 1;
    margin-right: 10rem;
    height: fit-content;
    display: flex;
    justify-content: space-between;
    margin-top: 5rem;
    align-items: center;
    background-color: #fff;
    overflow: hidden;
    border: 1rem solid $border-color;
    border-radius: 6rem;

    .icon {
      height: 40rem;
      line-height: 40rem;
      width: fit-content;
      font-size: 18rem;
      margin-right: 5rem;
      color: #aba8a8;
    }

    .name_input {
      outline: none;
      border: none;
      font-size: 14rem;
      height: 40rem;
      flex-grow: 1;


      padding-left: 8rem;
      padding-right: 8rem;
    }

  }
}


// 输入区域样式
.input-sections {
  width: 94vw;
  margin-top: 24rem;

  .input-section {
    margin-bottom: 24rem;
    width: 100%;
  }

  // 浮动标签容器
  .floating-label-container {
    position: relative;
    width: 100%;
  }

  // 浮动标签样式
  .floating-label {
    position: absolute;
    left: 14rem;
    top: 16rem;
    pointer-events: none;
    transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
    color: #8d8d8d;
    font-size: 15rem;
    padding: 0 4rem;
    background-color: transparent;
    opacity: 1;
  }

  // 激活状态
  .floating-label.active {
    top: -8rem;
    left: 12rem;
    font-size: 12rem;
    color: #8d8d8d;
    background-color: $lcbgc;
    opacity: 1;
  }

  // 输入框样式
  .feedback-input {
    width: 100%;
    padding: 8rem 8rem 8rem;
    border: 1rem solid $border-color;
    border-radius: 6rem;
    font-size: 14rem;
    background-color: $lcbgc;
    resize: none;
    transition: all 0.3s ease;
    line-height: 1.6;

    // &.focused {
    //   border-color: black;
    // }
  }

  // 字数统计样式
  .char-count {
    position: absolute;
    right: 12rem;
    bottom: 6rem;
    font-size: 12rem;
    color: #8d8d8d;
    opacity: 0.8;
  }

  // 总字数统计
  .total-char-count {
    text-align: right;
    font-size: 13rem;
    color: black;
    margin-top: 8rem;
    padding-top: 8rem;
    border-top: 1rem dashed $border-color;
    margin-bottom: 16rem;
  }
}

.o_w {
  height: 100vh;
  width: 100vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
}

// 模态框动画
@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20rem);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
